package com.medical.app.util;

import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;
import java.util.Base64;

@Component
public class ImageUtil {

    private static final Set<String> SUPPORTED_IMAGE_TYPES = Set.of(
            "image/jpeg", "image/jpg", "image/png", "image/gif", "image/bmp", "image/webp"
    );

    private static final long MAX_IMAGE_SIZE = 2 * 1024 * 1024;

    public Set<String> getSupportedImageTypes() {
        return new HashSet<>(SUPPORTED_IMAGE_TYPES);
    }

    public long getMaxImageSize() {
        return MAX_IMAGE_SIZE;
    }

    /**
     * 将图片文件转换为Base64字符串
     */
    public String convertToBase64(MultipartFile file) throws IOException {
        validateImageFile(file);

        byte[] fileContent = file.getBytes();
        String base64 = Base64.getEncoder().encodeToString(fileContent);

        String mimeType = file.getContentType();
        return "data:" + mimeType + ";base64," + base64;
    }

    /**
     * 将多个图片文件转换为Base64字符串列表
     */
    public List<String> convertMultipleToBase64(MultipartFile[] files) {
        if (files == null || files.length == 0) {
            return new ArrayList<>();
        }

        List<String> base64List = new ArrayList<>();
        for (MultipartFile file : files) {
            try {
                if (!file.isEmpty()) {
                    String base64 = convertToBase64(file);
                    base64List.add(base64);
                }
            } catch (IOException e) {
                // 跳过失败的文件，继续处理其他文件
            }
        }
        return base64List;
    }

    /**
     * 处理Base64图片数据
     */
    public List<String> processBase64Images(List<String> base64List) {
        if (base64List == null || base64List.isEmpty()) {
            return new ArrayList<>();
        }

        List<String> validBase64List = new ArrayList<>();
        for (String base64 : base64List) {
            if (isValidBase64(base64)) {
                validBase64List.add(base64);
            }
        }
        return validBase64List;
    }

    /**
     * 生成图片名称
     */
    public List<String> generateImageNames(List<String> base64List) {
        if (base64List == null || base64List.isEmpty()) {
            return new ArrayList<>();
        }

        List<String> names = new ArrayList<>();
        for (int i = 0; i < base64List.size(); i++) {
            String mimeType = extractMimeType(base64List.get(i));
            String extension = getFileExtension(mimeType);
            String name = "image_" + System.currentTimeMillis() + "_" + i + "." + extension;
            names.add(name);
        }
        return names;
    }

    /**
     * 从MIME类型获取文件扩展名
     */
    private String getFileExtension(String mimeType) {
        switch (mimeType) {
            case "image/jpeg":
            case "image/jpg":
                return "jpg";
            case "image/png":
                return "png";
            case "image/gif":
                return "gif";
            case "image/bmp":
                return "bmp";
            case "image/webp":
                return "webp";
            default:
                return "jpg";
        }
    }

    /**
     * 从Base64字符串中提取MIME类型
     */
    public String extractMimeType(String base64String) {
        if (base64String == null || !base64String.startsWith("data:")) {
            return "image/jpeg";
        }

        try {
            int semicolonIndex = base64String.indexOf(';');
            if (semicolonIndex > 0) {
                return base64String.substring(5, semicolonIndex);
            }
        } catch (Exception e) {
            // 忽略异常，返回默认类型
        }

        return "image/jpeg";
    }

    /**
     * 验证图片文件
     */
    private void validateImageFile(MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            throw new IOException("文件不能为空");
        }

        if (file.getSize() > MAX_IMAGE_SIZE) {
            throw new IOException("文件大小不能超过2MB");
        }

        String contentType = file.getContentType();
        if (contentType == null || !SUPPORTED_IMAGE_TYPES.contains(contentType.toLowerCase())) {
            throw new IOException("不支持的图片格式，仅支持: JPEG, PNG, GIF, BMP, WebP");
        }
    }

    /**
     * 检查Base64字符串是否有效
     */
    public boolean isValidBase64(String base64String) {
        if (base64String == null || base64String.isEmpty()) {
            return false;
        }

        try {
            String pureBase64 = base64String;
            if (base64String.startsWith("data:")) {
                int base64Index = base64String.indexOf("base64,");
                if (base64Index > 0) {
                    pureBase64 = base64String.substring(base64Index + 7);
                }
            }

            Base64.getDecoder().decode(pureBase64);
            return true;
        } catch (IllegalArgumentException e) {
            return false;
        }
    }

    /**
     * 从Base64字符串获取图片大小（字节）
     */
    public int getImageSizeFromBase64(String base64String) {
        if (!isValidBase64(base64String)) {
            return 0;
        }

        try {
            String pureBase64 = base64String;
            if (base64String.startsWith("data:")) {
                int base64Index = base64String.indexOf("base64,");
                if (base64Index > 0) {
                    pureBase64 = base64String.substring(base64Index + 7);
                }
            }

            byte[] decodedBytes = Base64.getDecoder().decode(pureBase64);
            return decodedBytes.length;
        } catch (IllegalArgumentException e) {
            return 0;
        }
    }
}